<template>
    <div class="TaskToolBar">
        <uni-popup ref="inputDialog" type="dialog" style="position: relative;z-index: 999">
            <uni-popup-dialog v-model="opinion"  ref="inputClose" mode="input" :title="opinionTitle"
                              :cancelText="$ti18('rxForm.cancelBtn', '取消')"
                              :confirmText="$ti18('rxForm.okBtn', '确定')"
                              :placeholder="i18n_('msg2','请输入意见')" @confirm="btnPendingOrRestore"></uni-popup-dialog>
        </uni-popup>
        <rx-button-list :localButtons="localButtons" @change="btnClick"></rx-button-list>
    </div>
</template>

<script>
import taskButton from './js/taskButton.js';
import formBase from './js/formBase.js';
import BpmtaskApi from "../../../api/rxBpm/bpmTask";
import BpmInstApi from "../../../api/rxBpm/bpmInst";
import BpmInstTrackedApi from "../../../api/rxBpm/bpmInstTracked";
import RxButtonList from "@/components/RxButtonList"
import Dialog from "@/js/Dialog";

export default {
    name: "TaskToolBar",
    mixins: [taskButton, formBase],
    components: {
        RxButtonList
    },
    props: {
       curData:{},
      bpmActionType: { type: String },
        bpmTaskDetail: {},
        taskConfig: {},
        canCommu: {
            default: true
        },
        appId: String,
    },
    data() {
        return {
            btns: [],
            showDisCardBtn: false,
            isCanBack: false,
            isTransferRoam: false,
            isCanRoamTransfer: false,
            isRoamTransferLog: false,
            isBatch: false,
            addSignBtn: false,


            backOptions: [],
            canCheck: true,
            allowApprove: {},
            canTransfer: '',
            candicate: -1,
            lockStatus: "",
            //保存状态
            showPendStore: false,
            visiableType: "",
            opinion: "",
            moreShow: false,
            opinionTitle:""
        }
    },
    computed: {
        //按钮数量
        buttonCount() {
            return this.taskConfig.maxButton || 5;
        },
        instId() {
            if (this.bpmTaskDetail && this.bpmTaskDetail.bpmInst) {
                return this.bpmTaskDetail.bpmInst.pkId;
            }
            return  "";
        },
        trackedTheme() {
            return this.bpmTaskDetail.tracked == '1' ? 'filled' : 'outlined';
        },
        trackText() {
            return this.bpmTaskDetail.tracked == "1" ? this.i18n_('Tracked','已跟踪') :this.i18n_('track','跟踪');
        },
        showMoreOptions() {
            let taskShowMore = this.taskConfig.switchOptions.includes("showMoreOptions");
            if (taskShowMore) {
                return true;
            }
            let rtn = this.parentVm.processConfig.switchOptions.includes("showMoreOptions");

            return rtn;
        }
    },
    methods: {
        i18n_(name,text,key){
            return this.$ti18(name,text,"bpmTaskLang.bpmOther",key);
        },
        //获取渲染表单对象
        getFormVm() {
            return this.parentVm.$refs.rxForms;
        },
        isBuildinBtn(btn) {
            let btns = ['btnApprove', 'btnSave', 'btnLock', 'btnAddSign',
                'btnReject', 'btnTransfer', 'btnDiscard',
                'btnCommu', 'btnCommuInfo', 'btnReply', 'btnPrint'];
            return btns.indexOf(btn) > -1;
        },
        btnClick(btn) {
            if (!this.isBuildinBtn(btn.id)) {
                this.handMethod(btn)
            } else {
                this[btn['method']](btn)
            }
        },
        getCandicate() {
            if (!this.bpmTaskDetail.bpmTask || !this.bpmTaskDetail.bpmTask.hasCandicate) {
                this.candicate = -1;
                this.lockStatus = "";
                return;
            }
            //有侯选人
            if (this.bpmTaskDetail.bpmTask.assignee) {
                this.candicate = 1;
                this.lockStatus = this.i18n_('releaseTask','释放任务');
            } else {
                this.candicate = 2;
                this.lockStatus =this.i18n_('lockTask','锁定任务');
            }
        },
        //保存草稿
        async doSaveData(callback) {
            let self = this;
            let formData = {};
            let data = {taskId: this.parentVm.taskId, systemHand: true};
            if (this.rxForms) {
                formData = this.rxForms.getData();
            }
            let formJson = JSON.stringify(formData);
            data.formJson = formJson;
            BpmtaskApi.saveFormData(data).then(resp => {
                uni.showToast({
                    title: resp.message, // 消息内容
                    duration: 2000, // 持续时间（单位：毫秒）
                    icon: 'none' // 图标类型（可选值：success/loading/none）
                });
                uni.navigateBack({
                    delta: 1,//返回层数，2则上上页
                })
            });
        },
        /*
        跟踪
         */
        doTracked() {
            let instId = this.bpmTaskDetail.bpmInst.instId;
            let self = this.parentVm;
            BpmInstTrackedApi.doTracked(instId).then(res => {
                uni.showToast({
                    title: res.message, // 消息内容
                    duration: 2000, // 持续时间（单位：毫秒）
                    icon: 'none' // 图标类型（可选值：success/loading/none）
                });
                self.loadTaskInfo();
            })
        },
        //是否可以审批
        canApprove() {
            if (!this.allowApprove.success) {
                this.$message.warn(this.allowApprove.message);

            }
            return this.allowApprove.success;
        },
        /*
        审批
         */
        async approve() {
            let formData = {};
            if (this.rxForms) {
                formData = this.rxForms.getData();
            }
            let parity = await this.rxForms.formCheckRule();
            if (!parity.success) {
                //校验不通过
                uni.showToast({
                    title: parity.msg, duration: 2000, icon: 'none'
                });
                return
            }
            //判断是否可以审批
            if (!this.canApprove()) {
                return;
            }
            let quickApprove = this.taskConfig.switchOptions.includes("quickApprove");
            if (quickApprove) {
                this.confirmApprove();
            } else {
                this.approveTask();
            }
        },
        /*
        快速审批
        */
        confirmApprove(){
            let self_ = this;
            uni.showModal({
                title:this.i18n_('tips','提示信息'),
                content:this.i18n_('confirmApprove','确定审批吗?'),
                success: function (res) {
                    if (res.confirm) {
                        self_.quickApprove();
                    } else if (res.cancel) {}
                }
            });
        },
        async quickApprove() {
            let parentVm = this.parentVm;
            if (parentVm.isCanRoamTransfer) {
                uni.showToast({
                    title:this.i18n_('approveTask','当前任务正在流转，请取消流转后重试!'), // 消息内容
                    duration: 2000, // 持续时间（单位：毫秒）
                    icon: 'none' // 图标类型（可选值：success/loading/none）
                });
                return;
            }
            let data = this.getApproveData();

            let cmd = {
                taskId: data.taskId,
                checkType: "AGREE",
                opinion: "",
                formJson: data.formJson,
                systemHand: true,
                //幂等号
                idempotenceid: parentVm.idempotenceid
            }
            let self_ = this;
            BpmtaskApi.checkComplete(cmd).then(resp => {
                if(resp.success){
                    uni.showToast({
                        title: '审批成功', // 消息内容
                        duration: 2000, // 持续时间（单位：毫秒）
                        icon: 'none' // 图标类型（可选值：success/loading/none）
                    });
                    self_.clickNavLeft(3)
                }else {
                    uni.showToast({
                        title: resp.message, // 消息内容
                        duration: 2000, // 持续时间（单位：毫秒）
                        icon: 'none' // 图标类型（可选值：success/loading/none）
                    });
                }

            })
        },
        /**
         * 流转情况
         */
        roamInfo(btn){
            let self = this.parentVm;
            let url = '/views/modules/bpm/task/BpmTaskRoamTransferDetail';
            url = url + '?taskId=' +self.taskId + '&appId=' + this.appId
            uni.navigateTo({url: url})
        },
        /*
        流转
         */
        doRoamTransfer() {
            if (!this.canApprove()) {
                return;
            }
            let self = this.parentVm;
            let data = {
                taskId: self.taskId,
                subject: self.bpmInst.subject,
            }
            let url = '/views/modules/bpm/task/BpmTaskRoamTransfer';
            url = url + '?data=' + JSON.stringify(data) + '&appId=' + this.appId
            uni.navigateTo({url: url})
        },
        /*
        取消流转
         */
        doCancelRoamTransfer() {
            let self_ = this
            uni.showModal({
                title:this.i18n_('tips','提示信息'),
                content:this.i18n_('cancelCirculation','确认取消流转任务吗？'),
                success: function (res) {
                    if (res.confirm) {
                        BpmtaskApi.cancelTransRoamTask(self_.parentVm.taskId).then(res => {
                            uni.showToast({
                                title: res.message, // 消息内容
                                duration: 2000, // 持续时间（单位：毫秒）
                                icon: 'none' // 图标类型（可选值：success/loading/none）
                            });
                            this.clickNavLeft(3)
                        })
                    }
                }
            });
        },
        /*
        转办
         */
        doTransfer() {
            if (!this.canApprove()) {
                return;
            }
            let self = this.parentVm;
            let data = {
                taskId: self.taskId,
                subject: self.bpmInst.subject,
            }
            let url = '/views/modules/bpm/task/BpmTaskTransferEdit';
            url = url + '?data=' + JSON.stringify(data) + '&appId=' + this.appId
            uni.navigateTo({url: url})
        },
        /*
        挂起
         */
        showPendingMode(btn) {
            if (!this.canApprove()) {
                return;
            }
            let title = this.i18n_('areyou','您确定要');
            let type = 'restore'; //默认 恢复时的参数；
            if (btn && btn.id == 'btnPending') {//挂起
                type = 'pending';
                title +=this.i18n_('Pending','挂起');
            }else{
                title +=this.i18n_('restore','恢复');
            }
            title += this.i18n_('currentTask','当前任务吗?');
            this.opinionTitle = title;
            this.visiableType = type;
            this.$refs.inputDialog.open()
        },
        //挂起或恢复
        btnPendingOrRestore() {
            let taskId = this.bpmTaskDetail.bpmTask.taskId;
            let self_ = this;
            BpmtaskApi.taskPendingOrRestore(taskId, this.visiableType, this.opinion).then(res => {
                if (res.success) {
                    uni.showToast({
                        title: res.message, // 消息内容
                        duration: 2000, // 持续时间（单位：毫秒）
                        icon: 'none' // 图标类型（可选值：success/loading/none）
                    });
                    uni.navigateBack({
                        delta: 1,//返回层数，2则上上页
                    })
                }
            });
        },
        /*
        作废
         */
        doDiscard() {
            let self_ = this
            uni.showModal({
                title:this.i18n_('tips','提示信息'),
                content:this.i18n_('CancelCurrentTask','您确定作废当前任务吗？'),
                confirmText: self_.$ti18('rxForm.okBtn', '确定'),
                cancelText: self_.$ti18('rxForm.cancelBtn', '取消'),
                success: function (res) {
                    if (res.confirm) {
                        BpmInstApi.cancelProcess(self_.instId, "").then(res => {
                            if (res.success) {
                                uni.showToast({
                                    title: res.message, // 消息内容
                                    duration: 2000, // 持续时间（单位：毫秒）
                                    icon: 'none' // 图标类型（可选值：success/loading/none）
                                });
                                uni.navigateBack({
                                    delta: 1
                                })
                            }
                        })
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });

        },
        /*
        沟通
         */
        communicate() {
            let self = this.parentVm;
            let data = {
                taskId: self.taskId,
                subject: self.bpmInst.subject,
            }
            let url = '/views/modules/bpm/task/BpmTaskLinkup';
            url = url + '?data=' + JSON.stringify(data) + '&appId=' + this.appId
            uni.navigateTo({url: url})
        },
        /*
        留言
         */
        doMessage() {
            let self = this.parentVm;
            let data = {
                instId: self.instId,
            }
            let url = '/views/modules/bpm/task/BpmAmessage';
            url = url + '?data=' + JSON.stringify(data) + '&appId=' + this.appId
            uni.navigateTo({url: url})
        },
        /*
       沟通情况
         */
        doCommuHistory() {
            let self = this.parentVm;
            let data = {
                instId: self.instId,
                taskId: self.taskId,
                nodeId: self.bpmTaskDetail.bpmTask ? self.bpmTaskDetail.bpmTask.key:"" ,
            }
            let url = '/views/modules/bpm/task/BpmCommuHistory';
            url = url + '?data=' + JSON.stringify(data) + '&appId=' + this.appId
            uni.navigateTo({url: url})

        },
        //驳回
        reject() {
            let self = this.parentVm;
            let bpmTaskDetail = this.bpmTaskDetail;
            uni.setStorageSync('bpmTaskDetail', JSON.stringify(bpmTaskDetail))
            let data = {
                taskId: self.taskId,
                instId: self.bpmInst.instId,
            }
            let url = '/views/modules/bpm/task/BpmTaskBack';
            url = url + '?data=' + JSON.stringify(data) + '&appId=' + this.appId
            uni.navigateTo({url: url})
        },
        async approveTask() {
            let self = this.parentVm;
            if (self.isCanRoamTransfer) {
                uni.showToast({
                    title:this.i18n_('approveTask','当前任务正在流转，请取消流转后重试!'), // 消息内容
                    duration: 2000, // 持续时间（单位：毫秒）
                    icon: 'none' // 图标类型（可选值：success/loading/none）
                });
                return;
            }
            let data = this.getApproveData();
            //显示更多选项。
            data.showMoreOptions = this.showMoreOptions;
            let self_ = this;
            let url = '/views/modules/bpm/task/BpmTaskCheck' + '?appId=' + this.appId;
            uni.setStorageSync('approveTask', JSON.stringify(data))
            uni.navigateTo({url: url})
        },
        getApproveData() {
            let self = this.parentVm;
            let data = {
                taskId: self.taskId,
                nodeExecutors: self.nodeExecutors,
                systemHand: true,
                taskConfig: this.taskConfig
            }
            let formData = this.rxForms.getData();
            let opinionName = this.rxForms.getOpinionName();
            data.opinionName = opinionName;
            let formJson = JSON.stringify(formData);
            data.formJson = formJson;
            return data;
        },
        /*
          打开表单
           */
        async openSolutionForm(btn) {
            let formBuild = this.getFormVm();
            let data = formBuild.data;
            let initData = this.getInitData(btn.config, data);
            let params = {
                alias: btn.config.formAlias,
                action: 'edit',
                jsonParams: initData
            }
            uni.navigateTo({
                url: '/views/modules/form/customForm/FormSolutionShow/FormSolutionComponent?params=' + JSON.stringify(params) + '&appId=' + this.appId
            })
        },
        /**
         * 根据配置 构建映射初始化数据
         * @param (Object) config 配置
         * @param data 当前表单数据
         * @returns (Object) 初始化数据
         */
        getInitData(config, data) {
            let formData = {};
            //根据配置 构建映射数据
            if (config.formConfig) {
                let formConfig = JSON.parse(config.formConfig);
                for (let i = 0; i < formConfig.length; i++) {
                    let obj = formConfig[i];
                    if (!obj.fieldConfig || obj.fieldConfig.length == 0) {
                        continue;
                    }
                    for (let j = 0; j < obj.fieldConfig.length; j++) {
                        let fieldConfig = obj.fieldConfig[j];
                        //映射到主表
                        if (obj.targetType == "main") {
                            //当前主表
                            if (fieldConfig.curType == "main") {
                                formData[fieldConfig.targetField] = data[fieldConfig.curField];
                            } else if (fieldConfig.curType == "onetoone") { //当前一对一子表
                                formData[fieldConfig.targetField] = data["sub__" + fieldConfig.curTable][fieldConfig.curField];
                            }
                        } else if (obj.targetType == "onetoone") {//映射到一对一子表
                            //一对一子表无数据时默认{}
                            if (!formData["sub__" + obj.targetTable]) {
                                formData["sub__" + obj.targetTable] = {};
                            }
                            //当前主表
                            if (fieldConfig.curType == "main") {
                                formData["sub__" + obj.targetTable][fieldConfig.targetField] = data[fieldConfig.curField];
                            } else if (fieldConfig.curType == "onetoone") { //当前一对一子表
                                formData["sub__" + obj.targetTable][fieldConfig.targetField] = data["sub__" + fieldConfig.curTable][fieldConfig.curField];
                            }
                        } else if (obj.targetType == "onetomany") {//映射到一对多子表
                            if (!formData["sub__" + obj.targetTable]) {
                                formData["sub__" + obj.targetTable] = [];
                            }
                            if (!formData.initData) {
                                formData.initData = {}
                            }
                            //子表一行的初始化数据
                            if (!formData.initData[obj.targetTable]) {
                                formData.initData[obj.targetTable] = {};
                            }
                            //当前主表
                            if (fieldConfig.curType == "main") {
                                formData.initData[obj.targetTable][fieldConfig.targetField] = data[fieldConfig.curField];
                                if (formData["sub__" + obj.targetTable] && formData["sub__" + obj.targetTable].length > 0) {
                                    for (let k = 0; k < formData["sub__" + obj.targetTable].length; k++) {
                                        formData["sub__" + obj.targetTable][k][[fieldConfig.targetField]] = data[fieldConfig.curField];
                                    }
                                }
                            } else if (fieldConfig.curType == "onetoone") { //当前一对一子表
                                formData.initData[obj.targetTable][fieldConfig.targetField] = data["sub__" + fieldConfig.curTable][fieldConfig.curField];
                                if (formData["sub__" + obj.targetTable] && formData["sub__" + obj.targetTable].length > 0) {
                                    for (let k = 0; k < formData["sub__" + obj.targetTable].length; k++) {
                                        formData["sub__" + obj.targetTable][k][[fieldConfig.targetField]] = data["sub__" + fieldConfig.curTable][fieldConfig.curField];
                                    }
                                }
                            } else {//当前一对多子表
                                if (!data["sub__" + fieldConfig.curTable]) {
                                    continue;
                                }
                                for (let k = 0; k < data["sub__" + fieldConfig.curTable].length; k++) {
                                    let row = data["sub__" + fieldConfig.curTable][k];
                                    //一对多子表单行无数据时默认{}
                                    if (!formData["sub__" + obj.targetTable][k]) {
                                        let subRow = JSON.parse(JSON.stringify(formData.initData[obj.targetTable]));
                                        subRow[fieldConfig.targetField] = row[fieldConfig.curField];
                                        formData["sub__" + obj.targetTable][k] = subRow;
                                    } else {
                                        formData["sub__" + obj.targetTable][k][fieldConfig.targetField] = row[fieldConfig.curField];
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return formData;
        },
        /*
        加签
         */
        addSign(btn) {
            let self = this.parentVm;
            let data = {
                taskId: self.taskId,
                instId: self.bpmInst.instId,
            }
            let url = '/views/modules/bpm/task/BpmTaskSign';
            url = url + '?data=' + JSON.stringify(data) + '&appId=' + this.appId
            uni.navigateTo({url: url})
        },
        /*
        审批历史
         */
        approvalHistory(btn){
            let self = this.parentVm;
            uni.navigateTo({
                url: '/views/modules/bpm/task/BpmApprovalHistory?instId=' + self.bpmInst.instId + '&appId=' + this.appId
            })
        },
        /*
        锁定任务
         */
        doLock(bth) {
            let self = this.parentVm;
            let title = this.candicate == 1 ?  this.i18n_('releaseTaskTips','释放任务吗?') : this.i18n_('lockTaskTips','锁定任务吗?');
            uni.showModal({
                title:this.i18n_('tips','提示信息'),
                content: title,
                success: function (res) {
                    if (res.confirm) {
                        let data = {taskId: self.taskId};
                        BpmtaskApi.updateLocked(data).then(resp => {
                            uni.showToast({
                                title: resp.message,
                                duration: 2000,
                                icon: 'none'
                            });
                            self.loadTaskInfo();
                        });
                    }
                }
            })
        },
        flowChart(bth){
            let self = this.parentVm;
            let formData = this.rxForms.getData();
            let conf = {
                data: {
                    taskId: self.taskId,
                    defId:self.bpmTask.defId,
                    formData:formData,
                    dialogOptions:{
                        title:this.i18n_('bpmImage','流程图'),
                        okText:''
                    },
                },
                curVm: this,
            };
            Dialog.openBpmImageView(conf, function (obj) {
            })
        },
    },
    watch: {
        bpmTaskDetail: {
            handler: function (val, oldval) {

                this.canCheck = val.canCheck;
                this.canTransfer = val.canTransfer;
                this.isCanBack = val.isCanBack;
                this.showDisCardBtn = val.isShowDiscardBtn;
                this.isTransferRoam = val.isTransferRoam;
                this.isCanRoamTransfer = val.isCanRoamTransfer;
                this.isRoamTransferLog = val.isRoamTransferLog;
                this.isBatch = val.isBatch;
                this.addSignBtn = val.canAddSign;
                this.allowApprove = val.allowApprove;
                this.backOptions = val.taskConfig.backOptions;
                this.getCandicate();
            },
            deep: true
        },
      curData:{
        handler(data){
          let val = this.bpmTaskDetail ;
          this.btns = this.changeBtnHandle(this.bpmActionType,val,val.taskConfig.buttons,data);
        },
        deep: true
      }

    },
}
</script>

<style scoped>
.TaskToolBar{
    width: 100%;
    display: flex;
}
</style>
